package com.dmagic.cms.common.security;

import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.dmagic.cms.common.util.ListUtil;
import com.dmagic.cms.entity.AppUser;
import com.dmagic.cms.entity.Permission;
import com.dmagic.cms.service.AppUserService;
import com.google.common.collect.Sets;

/**
 * implements SpringSecurity's UserDetailsService interface, get customer user
 * info Detail.
 * 
 * @author webster
 */
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {
	private static final Log logger = LogFactory.getLog(UserDetailsServiceImpl.class);

	@Autowired
	private AppUserService appUserService;

	/**
	 * loadUserByUsername
	 */
	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException,
			DataAccessException {
		logger.info("###################################userName:[" + userName + "]");
		AppUser appUser = null;
		try {
			appUser = appUserService.getAppUserByUserName(userName);
		} catch (Exception e) {
			throw new UsernameNotFoundException("", e);
		}
		if (appUser == null || ListUtil.isEmpty(appUser.getPermissions())) {
			throw new UsernameNotFoundException("userName is null or not exist!");
		}

		Set<GrantedAuthority> authSet = Sets.newHashSet();
		// every user has a default role
		authSet.add(new SimpleGrantedAuthority("ROLE_DEFAULT_GUESTUSER"));
		for (Permission permission : appUser.getPermissions()) {
			authSet.add(new SimpleGrantedAuthority(permission.getPermissionName()));
		}

		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		UserDetails userDetail = new User(userName, appUser.getPassword(), enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authSet);
		logger.info("UserName:[" + userName + "],has roleList：{" + userDetail.getAuthorities().toString()
				+ "}");
		return userDetail;
	}

}
